package com.example.chapter06;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.example.chapter06.util.FileUtil;
import com.example.chapter06.util.ToastUtil;

import java.io.File;

public class FileWriteActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_name, et_age, et_height, et_weight;
    private CheckBox ck_married;
    private String path;
    private TextView tv_txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_write);

        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        ck_married = findViewById(R.id.ck_married);
        tv_txt = findViewById(R.id.tv_txt);  // 读取文本的TextView
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_save) {
            String name = et_name.getText().toString();
            String age = et_age.getText().toString();
            String height = et_height.getText().toString();
            String weight = et_weight.getText().toString();

            StringBuilder sb = new StringBuilder();
            sb.append("name: ").append(name).append("\n");
            sb.append("age: ").append(age).append("\n");
            sb.append("height: ").append(height).append("\n");
            sb.append("weight: ").append(weight).append("\n");
            sb.append("married: ").append(ck_married.isChecked()).append("\n");

            String directory = null;
            // 获取外部存储的的私有空间
            directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
            // 获取外部存储的公共空间
            directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            // 获取内部存储的私有空间
            directory = getFilesDir().toString();
            String fileName = System.currentTimeMillis() + ".txt";
            path = directory + File.separatorChar + fileName;
            FileUtil.saveText(path, sb.toString());
            ToastUtil.show(this, "数据已保存到" + path);

        } else if (v.getId() == R.id.btn_read) {
            String s = FileUtil.openText(path);
            tv_txt.setText(s);
        }
    }
}